/*
 * main.cpp
 *
 *  Created on: 05.06.2012
 *      Author: sebastian
 */

#include <iostream>

#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>

#define PORT 8080

#define handle_error(msg) \
           do { perror(msg); exit(EXIT_FAILURE); } while (0)


//nice... http://www.c-plusplus.de/forum/169861-full
//http://www.c-worker.ch/tuts/wstut_op.php
//even nicer:
//http://www.fh-gelsenkirchen.de/fb01/homepages/pollakowski/socket/skripte/ServerHalloWelt.txt

using namespace std;


void perror(const char * msg) {
	cout << "ERROR: " << msg << endl;
}

std::string intToStr(int i) {
	//get length of i....
	int c = 1;
	for (int a=i; a/10.0 >= 1; a/=10)
		c++;
	char s[c];
	sprintf(s, "%i", i);
	string res = s;
	return res;
}

int main() {
	int s, c;

	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(struct sockaddr_in));
	addr.sin_family = AF_INET;
	addr.sin_port=htons(PORT);

	addr.sin_addr.s_addr = INADDR_ANY;


	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s == -1) handle_error("socket");

	if (bind(s, (struct sockaddr *) &addr,
		sizeof(addr)) == -1)
		handle_error("bind");

	if (listen(s, 3) == -1)
		handle_error("listen");


	bool isRunning = true;
	while (isRunning) {
		c = accept(s, NULL, NULL);
		if (c == -1)
			handle_error("accept");
		else {

			string body, header;

			body = "<html><body><h1>Happy New Millennium!</h1>(more file contents)</body></html>";
			header = "HTTP/1.0 200 OK\nContent-Type: text/html\nContent-Length: "+intToStr(body.length());


			string msg = header+"\n\n"+body;
			cout << "sending...\n" << msg.c_str();

			send(c, msg.c_str(), msg.length(), 0);
			//send(c, msg.c_str(), msg.length(),0 );

			//TODO: handle sentBytes!

		}
		close(c);

	}

	close(s);

	return 0;




}


